import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/foundation.dart';
import '../models/learning_item.dart';
import '../models/learning_data_service.dart';
import '../models/recommendation_service.dart';
import '../models/user_preference.dart';
import '../models/category_service.dart';
import '../models/shared_recommendation_service.dart';
import 'category_screen.dart';
import '../widgets/learning_card.dart';
import '../widgets/custom_page_controller.dart';
import '../widgets/gesture_handler.dart';
import '../widgets/animated_card_container.dart';
import 'package:flutter/services.dart'; // 添加系统服务导入

/// 推荐参数类，用于compute函数传递参数
class _RecommendationParams {
  final List<LearningItem> allItems;
  final UserPreference preference;
  final Set<String> excludedIds;
  final int count;

  _RecommendationParams({
    required this.allItems,
    required this.preference,
    required this.excludedIds,
    required this.count,
  });

  /// 转换为Map以便在compute中传递
  Map<String, dynamic> toMap() {
    return {
      'allItems': allItems,
      'preference': preference,
      'excludedIds': excludedIds.toList(),
      'count': count,
    };
  }

  /// 从Map恢复参数
  static _RecommendationParams fromMap(Map<String, dynamic> map) {
    return _RecommendationParams(
      allItems: List<LearningItem>.from(map['allItems']),
      preference: map['preference'],
      excludedIds: Set<String>.from(map['excludedIds']),
      count: map['count'],
    );
  }
}

class MainScreen extends StatefulWidget {
  final LearningItem? filterItem;
  final LearningItem? singleItem;
  final int initialIndex;
  
  const MainScreen({super.key, this.filterItem, this.singleItem, this.initialIndex = 0});

  @override
  State<MainScreen> createState() => _MainScreenState();
}

class _MainScreenState extends State<MainScreen> {
  late final CustomPageController _pageController;
  int _currentPage = 0;
  List<LearningItem> _items = [];
  List<LearningItem> _allItems = []; // 存储所有项目
  Set<String> _shownItemIds = <String>{}; // 记录已展示过的项目ID
  bool _isLoading = true;
  bool _isLoadingMore = false; // 是否正在加载更多
  UserPreference _userPreference = UserPreference();

  @override
  void initState() {
    super.initState();
    _pageController = CustomPageController();
    _pageController.addListener(_onPageChanged);
    
    // 添加共享推荐服务监听器
    SharedRecommendationService.instance.addListener(_onSharedDataUpdated);
    
    // 使用addPostFrameCallback确保在第一帧渲染后才加载数据
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadItems();
    });
  }

  @override
  void dispose() {
    // 移除共享推荐服务监听器
    SharedRecommendationService.instance.removeListener(_onSharedDataUpdated);
    _pageController.removeListener(_onPageChanged);
    _pageController.dispose();
    super.dispose();
  }

  /// 处理共享数据更新
  void _onSharedDataUpdated() {
    print('Shared data updated');
    // 从共享服务获取最新数据
    final sharedItems = SharedRecommendationService.instance.recommendedItems;
    final sharedAllItems = SharedRecommendationService.instance.allItems;
    final sharedPreference = SharedRecommendationService.instance.userPreference;
    
    setState(() {
      _items = sharedItems;
      _allItems = sharedAllItems;
      _userPreference = sharedPreference;
      
      // 更新已展示项目ID集合
      _shownItemIds.clear();
      for (var item in _items) {
        _shownItemIds.add(item.id);
      }
      
      _isLoading = false;
    });
    
    print('Updated items from shared service: ${_items.length}');
  }

  /// 更新推荐内容
  void _updateRecommendations() async {
    try {
      // 使用compute函数将计算密集型任务放到后台线程执行
      final recommendedItems = await compute(
        _recommendItemsWithExclusion,
        _RecommendationParams(
          allItems: _allItems,
          preference: _userPreference,
          excludedIds: _shownItemIds,
          count: 20,
        ).toMap(),
      );
      
      // 更新本地推荐数据
      setState(() {
        _items = recommendedItems;
        // 更新已展示项目ID集合
        _shownItemIds.clear();
        for (var item in recommendedItems) {
          _shownItemIds.add(item.id);
        }
      });
      
      print('Updated recommendations: ${_items.length} items');
    } catch (e) {
      print('Error updating recommendations: $e');
    }
  }

  /// 从JSON文件加载学习项数据
  void _loadItems() async {
    print('Starting to load items...');
    try {
      // 如果有singleItem，则只显示这一项
      if (widget.singleItem != null) {
        print('Loading single item: ${widget.singleItem!.title}');
        setState(() {
          _allItems = [widget.singleItem!];
          _items = [widget.singleItem!];
          _shownItemIds.clear();
          _shownItemIds.add(widget.singleItem!.id);
          _isLoading = false;
        });
        return;
      }
      
      // 从共享服务获取数据
      final sharedItems = SharedRecommendationService.instance.recommendedItems;
      final sharedAllItems = SharedRecommendationService.instance.allItems;
      final sharedPreference = SharedRecommendationService.instance.userPreference;
      
      // 如果共享服务中有数据，则使用这些数据
      if (sharedItems.isNotEmpty) {
        print('Loading items from shared service, count: ${sharedItems.length}');
        setState(() {
          _items = sharedItems;
          _allItems = sharedAllItems;
          _userPreference = sharedPreference;
          
          // 更新已展示项目ID集合
          _shownItemIds.clear();
          for (var item in sharedItems) {
            _shownItemIds.add(item.id);
          }
          
          _isLoading = false;
        });
        
        // 如果有初始索引，则跳转到该索引
        if (widget.initialIndex > 0 && widget.initialIndex < sharedItems.length) {
          WidgetsBinding.instance.addPostFrameCallback((_) {
            _pageController.jumpToPage(widget.initialIndex);
          });
        }
        return;
      }
      
      // 如果共享服务中没有数据，则从文件加载
      final allItems = await LearningDataService.loadLearningItems();
      SharedRecommendationService.instance.updateAllItems(allItems);
      print('All items loaded: ${allItems.length}');
      
      // 如果有filterItem，则只使用匹配的项目
      List<LearningItem> filteredItems = allItems;
      if (widget.filterItem != null) {
        print('Filtering items by: ${widget.filterItem!.title}');
        // 根据不同的内容类型进行过滤
        if (widget.filterItem!.tags.contains('pinyin')) {
          // 如果是拼音类型，只显示拼音相关的项目
          filteredItems = allItems.where((item) => item.tags.contains('pinyin')).toList();
          print('Filtered pinyin items: ${filteredItems.length}');
        } else if (widget.filterItem!.contentRef != null && 
                   widget.filterItem!.contentRef!.contains('vocabulary_data')) {
          // 如果是词汇类型，只显示词汇相关的项目
          filteredItems = allItems.where((item) => item.contentRef != null && 
                                         item.contentRef!.contains('vocabulary_data')).toList();
          print('Filtered vocabulary items: ${filteredItems.length}');
        } else if (widget.filterItem!.subject == 'Film') {
          // 如果是电影类型，只显示电影相关的项目
          filteredItems = allItems.where((item) => item.subject == 'Film').toList();
          print('Filtered film items: ${filteredItems.length}');
        } else if (widget.filterItem!.contentRef != null) {
          // 根据contentRef进行过滤
          filteredItems = allItems.where((item) => item.contentRef == widget.filterItem!.contentRef).toList();
          print('Filtered by contentRef items: ${filteredItems.length}');
        }
      }
      
      // 生成推荐数据
      final recommendedItems = await SharedRecommendationService.instance.generateRecommendations(
        count: 20,
      );
      
      setState(() {
        _allItems = filteredItems; // 保存过滤后的所有项目
        _items = recommendedItems;
        
        print('Recommended initial items: ${_items.length}');
        // 记录初始展示的项目ID
        _shownItemIds.clear();
        for (var item in _items) {
          _shownItemIds.add(item.id);
        }
        
        _isLoading = false;
      });
      
      print('Loaded initial items: ${_items.length}, total items: ${_allItems.length}, shown items: ${_shownItemIds.length}');
    } catch (e) {
      print('Error loading items: $e');
      setState(() {
        _isLoading = false;
      });
    }
  }

  /// 当页面改变时调用
  void _onPageChanged() {
    final page = _pageController.page?.round() ?? 0;
    if (page != _currentPage) {
      setState(() {
        _currentPage = page;
      });
      
      // 如果接近末尾，加载更多
      if (page >= _items.length - 3) {
        _loadMoreItems();
      }
    }
  }

  /// 加载更多项目
  void _loadMoreItems() async {
    print('=== STARTING LOAD MORE ITEMS FUNCTION ===');
    print('Current items: ${_items.length}, shown items: ${_shownItemIds.length}, loading more: $_isLoadingMore');
    
    // 如果正在加载更多，或者没有更多项目，直接返回
    if (_isLoadingMore || _allItems.isEmpty || _items.isEmpty) {
      print('Skipping load more: isLoadingMore=$_isLoadingMore, allItemsEmpty=${_allItems.isEmpty}, itemsEmpty=${_items.isEmpty}');
      return;
    }

    setState(() {
      _isLoadingMore = true;
    });
    
    try {
      print('Loading more items...');
      
      // 推荐更多项目（每次加载10个）
      // 使用compute函数将计算密集型任务放到后台线程执行
      final moreItems = await compute(
        _recommendItemsWithExclusion,
        _RecommendationParams(
          allItems: _allItems,
          preference: _userPreference,
          excludedIds: _shownItemIds,
          count: 10,
        ).toMap(),
      );
      
      print('Recommended ${moreItems.length} new items');
      
      if (moreItems.isNotEmpty) {
        final previousLength = _items.length;
        setState(() {
          _items.addAll(moreItems);
          // 记录新展示的项目ID
          for (var item in moreItems) {
            _shownItemIds.add(item.id);
          }
          _isLoadingMore = false;
        });
        print('SUCCESSFULLY ADDED ${moreItems.length} items (from $previousLength to ${_items.length})');
        print('Total shown items now: ${_shownItemIds.length}');
      } else {
        print('NO MORE ITEMS TO LOAD, items will repeat');
        setState(() {
          _isLoadingMore = false;
        });
        // 如果没有更多项目，清空已展示集合以允许重复展示
        if (_shownItemIds.length >= _allItems.length) {
          print('Clearing shown items to allow repeating');
          setState(() {
            _shownItemIds.clear();
          });
        }
      }
    } catch (e) {
      print('Error loading more items: $e');
      setState(() {
        _isLoadingMore = false;
      });
    }
    
    print('=== END OF LOAD MORE ITEMS FUNCTION ===');
  }

  /// 在后台线程执行的推荐算法
  static List<LearningItem> _recommendItemsWithExclusion(Map<String, dynamic> paramsMap) {
    final params = _RecommendationParams.fromMap(paramsMap);
    // 使用本地数据而不是服务中的数据，因为我们在后台线程中
    return RecommendationService.recommendItemsWithExclusion(
      params.allItems,
      params.preference,
      params.excludedIds,
      count: params.count,
    );
  }

  /// 处理点赞事件
  void _handleLike(LearningItem item) {
    print('Liked item: ${item.title}');
    // 可以在这里更新用户偏好
  }

  /// 处理不喜欢事件
  void _handleDislike(LearningItem item) {
    print('Disliked item: ${item.title}');
    // 可以在这里更新用户偏好
  }

  /// 显示分类选择界面
  void _showCategorySelection() {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => const CategoryScreen(),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    print('Building MainScreen with ${_items.length} items, current page: $_currentPage');
    
    if (_isLoading) {
      return const Scaffold(
        body: Center(
          child: CircularProgressIndicator(),
        ),
      );
    }

    // 如果没有项目可显示
    if (_items.isEmpty) {
      return const Scaffold(
        body: Center(
          child: Text('没有可显示的学习内容'),
        ),
      );
    }

    return Scaffold(
      body: PageView.builder(
        scrollDirection: Axis.vertical, // 改为垂直滑动
        controller: _pageController,
        itemCount: _items.length + (_isLoadingMore ? 1 : 0), // 添加加载状态项
        itemBuilder: (context, index) {
          print('Building page for index: $index, items length: ${_items.length}');
          
          // 如果是加载状态项
          if (_isLoadingMore && index == _items.length) {
            return const Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  CircularProgressIndicator(),
                  SizedBox(height: 16),
                  Text('正在加载更多内容...'),
                ],
              ),
            );
          }
          
          // 如果索引超出范围
          if (index >= _items.length) {
            return const Center(
              child: Text('没有更多内容'),
            );
          }
          
          final item = _items[index];
          print('Building LearningCard for item: ${item.title} (ID: ${item.id})');
          
          return AnimatedCardContainer(
            isActive: true,
            child: LearningCard(
              item: item,
              onLike: () => _handleLike(item),
              onDislike: () => _handleDislike(item),
              onCategory: _showCategorySelection,
              onPageSwitch: () {
                // 切换到下一页
                _pageController.animateToNextPage();
              },
            ),
          );
        },
      ),
    );
  }
}
